/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package loja.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import loja.dao.exceptions.BuscaException;
import loja.dao.exceptions.ImpossivelAtualizarException;
import loja.dao.exceptions.ImpossivelCriarException;
import loja.dao.exceptions.ImpossivelDeletarException;

/**
 *
 * @author Administrador
 */
public abstract class AbstractGenericDao<T> {

    protected Connection conexao;

    public Connection getConexao() throws SQLException {
        if (conexao == null) {
            conexao = JdbcUtils.getConexao();
        }
        return conexao;
    }

    public void setConexao(Connection conexao) {
        this.conexao = conexao;
    }

    public abstract void criar(T t) throws ImpossivelCriarException;

    public abstract void atualizar(T t) throws ImpossivelAtualizarException;

    public abstract void deletar(T t) throws ImpossivelDeletarException;

    public abstract T buscar(Long id) throws BuscaException;

    public abstract List<T> buscarTodos() throws BuscaException;

    public abstract long contar() throws BuscaException;

    public java.sql.Date dateUtilToDateSql(java.util.Date dateUtil) {
        return new java.sql.Date(dateUtil.getTime());
    }

    public java.util.Date dateSqlToDateUtil(java.sql.Date dateSql) {
        return new java.util.Date(dateSql.getTime());
    }

    protected void iniciarTransacao() throws SQLException {
        conexao = JdbcUtils.getConexao();
        conexao.setAutoCommit(false);
    }

    protected void comitarTransacao() throws SQLException {
        conexao.commit();
        conexao.setAutoCommit(true);
    }

    protected void cancelarTransacao(Exception ex, Class classe) {
        try {
            conexao.rollback();
            Logger.getLogger(classe.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex1) {
            Logger.getLogger(AbstractGenericDao.class.getName()).log(Level.SEVERE, null, ex1);
        }

    }

    protected void closeStatement(Statement stmt) {
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException ex) {
        }
    }

    protected void closeResultSet(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException ex) {
        }
    }

    protected void closeResultSetAndStatement(ResultSet rs, Statement stmt) {
        closeResultSet(rs);
        closeStatement(stmt);
    }
}
